package com.ruoyi.project.jiaqin.supply.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.jiaqin.company.domain.Company;
import com.ruoyi.project.jiaqin.company.service.ICompanyService;
import com.ruoyi.project.jiaqin.followcompany.domain.JiaqinFollowCompany;
import com.ruoyi.project.jiaqin.followcompany.service.IJiaqinFollowCompanyService;
import com.ruoyi.project.jiaqin.followmember.domain.JiaqinFollowMember;
import com.ruoyi.project.jiaqin.followmember.service.IJiaqinFollowMemberService;
import com.ruoyi.project.jiaqin.quotationclass.domain.QuotationClass;
import com.ruoyi.project.jiaqin.quotationclass.mapper.QuotationClassMapper;
import com.ruoyi.project.jiaqin.region.domain.Region;
import com.ruoyi.project.jiaqin.region.service.IRegionService;
import com.ruoyi.project.jiaqin.supply.domain.Supply;
import com.ruoyi.project.jiaqin.supply.mapper.SupplyMapper;
import com.ruoyi.project.jiaqin.supply.service.ISupplyService;
import com.ruoyi.project.jiaqin.supplyclass.service.ISupplyClassService;
import com.ruoyi.project.jiaqin.supplycollect.domain.JiaqinSupplyCollect;
import com.ruoyi.project.jiaqin.supplycollect.mapper.JiaqinSupplyCollectMapper;
import com.ruoyi.project.jiaqin.supplycollect.service.IJiaqinSupplyCollectService;
import com.ruoyi.project.jiaqin.supplyimg.domain.SupplyImg;
import com.ruoyi.project.jiaqin.supplyimg.mapper.SupplyImgMapper;
import com.ruoyi.project.jiaqin.val.domain.ClassAttrVal;
import com.ruoyi.project.jiaqin.val.service.IClassAttrValService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.mapper.MemberMapper;
import com.ruoyi.project.system.member.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 供应Service业务层处理
 *
 * @author admin
 * @date 2020-12-28
 */
@Service
public class SupplyServiceImpl implements ISupplyService
{
    @Autowired
    private SupplyMapper supplyMapper;
    @Autowired
    private QuotationClassMapper quotationClassMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IClassAttrValService iClassAttrValService;
    @Autowired
    private IJiaqinSupplyCollectService iJiaqinSupplyCollectService;
    @Autowired
    private ICompanyService iCompanyService;
    @Autowired
    private IJiaqinFollowMemberService jiaqinFollowMemberService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private ISupplyClassService supplyClassService;
    @Autowired
    private IJiaqinFollowCompanyService jiaqinFollowCompanyService;
    @Autowired
    private ICompanyService companyService;

    /**
     * 查询供应
     *
     * @param id 供应ID
     * @return 供应
     */
    @Override
    public Supply selectSupplyById(String id)
    {
        return supplyMapper.selectSupplyById(id);
    }

    @Autowired
    private SupplyImgMapper supplyImgMapper;
    @Override
    public JSONObject supplyDeatil(String id,String userId) {

        JSONObject data = new JSONObject();
        Supply supply = supplyMapper.selectSupplyById(id);
        QuotationClass oneClass = quotationClassMapper.selectQuotationClassById(supply.getOneClassId());
        QuotationClass twoClass = quotationClassMapper.selectQuotationClassById(supply.getTwoClassId());
        QuotationClass thrClass = quotationClassMapper.selectQuotationClassById(supply.getThrClassId());
        Member releaseMember = memberMapper.selectMemberById(supply.getReleaseMember());
        Company company = null;
        if(releaseMember != null){
            if(releaseMember.getIsCompany() == 1){
                //查企业信息
                company = iCompanyService.selectCompanyByMemberId(releaseMember.getId());
            }
        }
        Region province = regionService.selectRegionById(supply.getProvince());
        Region city = regionService.selectRegionById(supply.getCity());
        Region area = regionService.selectRegionById(supply.getArea());
        List<ClassAttrVal> attrValList = new ArrayList<>();
        if(supply.getAttrVals()!= null){
            String[] srr = supply.getAttrVals().split(",");
            for (String s: srr) {
                attrValList.add(iClassAttrValService.selectClassAttrValById(s));
            }
        }
        //判断是否收藏
        JiaqinSupplyCollect jiaqinSupplyCollect = iJiaqinSupplyCollectService.selectJiaqinSupplyCollectByMemberIdAndToSupplyId(userId,releaseMember.getId());
        if(jiaqinSupplyCollect == null){
            //未收藏
            supply.setCollect(false);
        }else{
            supply.setCollect(true);
        }
        // 判断是否关注
        Supply supplyById = supplyService.selectSupplyById(id);// 供应
        if (supplyById != null) {
            Member memberById = memberService.selectMemberById(supplyById.getReleaseMember());// 用户
            if (memberById != null) {
                Company companyById = companyService.selectCompanyByMemberId(memberById.getId());// 企业
                // 有企业
                if (companyById != null) {
                    JiaqinFollowCompany jiaqinFollowCompany = jiaqinFollowCompanyService.selectJiaqinFollowMemberByMemberIdAndToCompanyId(userId, companyById.getId());// 是否关注
                    // 已关注企业
                    if (jiaqinFollowCompany != null) {
                        supply.setIsFollow(1);
                    } else {// 未关注企业
                        supply.setIsFollow(0);
                    }
                } else {// 无企业
                    JiaqinFollowMember jiaqinFollowMember = jiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(userId, supplyById.getReleaseMember());
                    // 已关注个人
                    if (jiaqinFollowMember != null) {
                        supply.setIsFollow(1);
                    } else {
                        // 未关注个人
                        supply.setIsFollow(0);
                    }
                }
            }
        }
        SupplyImg supplyImg = new SupplyImg();
        supplyImg.setSupplyId(id);
        List<SupplyImg> supplyImgList = supplyImgMapper.selectSupplyImgList(supplyImg);
        data.put("supply",supply);
        data.put("oneClass",oneClass);
        data.put("twoClass",twoClass);
        data.put("thrClass",thrClass);
        data.put("releaseMember",releaseMember);
        data.put("company",company);
        data.put("province",province);
        data.put("city",city);
        data.put("area",area);
        data.put("attrValList",attrValList);
        data.put("supplyImgList",supplyImgList);
        return data;
    }

    /**
     * 查询供应列表
     *
     * @param supply 供应
     * @return 供应
     */
    @Override
    public List<Supply> selectSupplyList(Supply supply)
    {
        return supplyMapper.selectSupplyList(supply);
    }

    @Override
    public PageInfo<Supply> getSupply(Integer pageNum, Integer pageSize, Supply supply) {
        //没传发布人查全部（排序方式）
        if (supply.getReleaseMember() == null) {
            if(supply.getSortField() == null || supply.getSortField().equals("")){
                PageHelper.startPage(pageNum,pageSize,"views desc");
            }else{
                PageHelper.startPage(pageNum,pageSize,supply.getSortField() + " "+supply.getSortType());
            }
        }

//        supply.setStatus(0);//查询已上架的
        List<Supply> list = supplyMapper.selectSupplyList(supply);
        for (Supply s : list) {
            Member memberById = memberService.selectMemberById(s.getReleaseMember());
            if (memberById != null) {
                Company company = companyService.selectCompanyByMemberId(memberById.getId());
                if (company != null) {
                    s.setHeadpic(company.getCompanyAvatar());
                    s.setMemberName(company.getCompanyName());
                    s.setQuotation(company.getQuotation());
                } else {
                    s.setHeadpic(memberById.getHeadpic());
                    s.setMemberName(memberById.getUsername());
                    s.setQuotation(memberById.getQuotation());
                }
            }
        }
        PageInfo<Supply> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 新增供应
     *
     * @param supply 供应
     * @return 结果
     */
    @Override
    public int insertSupply(Supply supply)
    {
//        supply.setId(UUID.randomUUID().toString().replace("-",""));
        return supplyMapper.insertSupply(supply);
    }

    /**
     * 修改供应
     *
     * @param supply 供应
     * @return 结果
     */
    @Override
    public int updateSupply(Supply supply)
    {
        return supplyMapper.updateSupply(supply);
    }

    /**
     * 删除供应对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSupplyByIds(String ids)
    {
        return supplyMapper.deleteSupplyByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除供应信息
     *
     * @param id 供应ID
     * @return 结果
     */
    @Override
    public int deleteSupplyById(String id)
    {
        return supplyMapper.deleteSupplyById(id);
    }

    @Autowired
    private JiaqinSupplyCollectMapper jiaqinSupplyCollectMapper;
    @Autowired
    private ISupplyService supplyService;
    @Override
    public PageInfo<JiaqinSupplyCollect> getFocusOnSupply(Integer pageNum, Integer pageSize, String memberId) {
        // 查询我关注的人
//        JiaqinFollowMember followMember = new JiaqinFollowMember();
//        followMember.setMemberId(memberId);
//        List<JiaqinFollowMember> followMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(followMember);
//
//        List<Object> arrayList = new ArrayList<>();
//
//        if (followMemberList != null && followMemberList.size() != 0) {
//            for (JiaqinFollowMember JFM : followMemberList) {
//                // 查询我关注的人发布的供应
//                PageHelper.startPage(pageNum,pageSize);
//                List<Supply> supplyList = supplyMapper.getFocusOnSupply(JFM.getFollowMemberId());
//
//                if (supplyList != null && supplyList.size() != 0) {
//                    for (Supply S : supplyList) {
//                        // 关联我关注的人发布的供应信息
//                        Supply supplyById = supplyMapper.selectSupplyById(S.getId());
//                        if (supplyById != null) {
//                            SupplyClass supplyClassByOne = supplyClassService.selectSupplyClassById(supplyById.getOneClassId());
//                            SupplyClass supplyClassByTwo = supplyClassService.selectSupplyClassById(supplyById.getTwoClassId());
//                            SupplyClass supplyClassByThr = supplyClassService.selectSupplyClassById(supplyById.getThrClassId());
//                            if (supplyClassByOne != null) {
//                                S.setOneClassId(supplyClassByOne.getName());
//                            }
//                            if (supplyClassByTwo != null) {
//                               S.setTwoClassId(supplyClassByTwo.getName());
//                            }
//                            if (supplyClassByThr != null) {
//                                S.setThrClassId(supplyClassByThr.getName());
//                            }
//                            Member memberById = memberService.selectMemberById(supplyById.getReleaseMember());
//                            if (memberById != null) {
//                                S.setReleaseMember(memberById.getUsername());
//                            }
//                        }
//                    }
//                }
//                arrayList.add(supplyList);
//            }
//        }
//        PageInfo<Object> pageInfo = new PageInfo<>(arrayList);
//        return pageInfo;
        PageHelper.startPage(pageNum,pageSize);
        List<JiaqinSupplyCollect> list = jiaqinSupplyCollectMapper.selectJiaqinSupplyCollectByMemberId(memberId);
        if(list != null && list.size()!= 0){
            for (JiaqinSupplyCollect JSC :list) {
                Supply supplyById = supplyService.selectSupplyById(JSC.getSupplyId());
                if(supplyById != null) {
                    Member memberById = memberService.selectMemberById(supplyById.getReleaseMember());
                    String[] imgUrls = supplyById.getImgUrls().split(",");
                    supplyById.setImgUrls(imgUrls[0]);
                    JSC.setSupply(supplyById);
                    if (memberById != null) {
                        Company company = companyService.selectCompanyByMemberId(memberById.getId());
                        if (company != null) {
                            supplyById.setReleaseMember(company.getCompanyName());
                            supplyById.setHeadpic(company.getCompanyAvatar());
                            supplyById.setIsCompany(1);
                            supplyById.setMemberCompanyId(company.getId());
                        } else {
                            supplyById.setReleaseMember(memberById.getUsername());
                            supplyById.setHeadpic(memberById.getHeadpic());
                            supplyById.setIsCompany(0);
                            supplyById.setMemberCompanyId(memberById.getId());
                        }

                    }
                }
            }
        }
        PageInfo<JiaqinSupplyCollect> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<Supply> getSupplyListByMemberId(Integer pageNum, Integer pageSize, String memberId) {

        List<Supply> list = supplyMapper.getSupplyListByMemberId2(memberId);
        PageHelper.startPage(pageNum,pageSize);
        List<Supply> newList = new ArrayList<Supply>();
        Set<String> set = new HashSet<String>();
        for (Supply S : list) {
            String userId = S.getReleaseMember();
            if (!set.contains(userId)) {//set中不包含重复的
                set.add(userId);
                String[] imgUrls = S.getImgUrls().split(",");
                S.setImgUrls(imgUrls[0]);
                Company company = companyService.selectCompanyByMemberId(S.getReleaseMember());
                Member member = memberService.selectMemberById(S.getReleaseMember());
                if (company != null) {
                    S.setIsCompany(1);
                    S.setMemberName(company.getCompanyName());
                    S.setHeadpic(company.getCompanyAvatar());
                } else {
                    S.setIsCompany(0);
                    S.setMemberName(member.getUsername());
                    S.setHeadpic(member.getHeadpic());
                }
                S.setMemberCompanyId(S.getReleaseMember());
                newList.add(S);
            }
            // 关注供应列表每一条数字提示
            JiaqinFollowMember followMember = jiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(memberId, userId);
            if (followMember != null && followMember.getSupplyNum() == 1) {
                List<Supply> list1 = supplyMapper.getSupplyNumByMemberId(userId);
                S.setSupplyNum(list1.size());
            } else {
                S.setSupplyNum(0);
            }
        }
        PageInfo<Supply> pageInfo = new PageInfo<>(newList);
        return pageInfo;
    }

    @Override
    public List<Supply> getSupplyListByMemberId2(String memberId) {
        return supplyMapper.getSupplyListByMemberId2(memberId);
    }

    @Override
    public PageInfo<Supply> getFocusOnSupplyByFollowMemberId(Integer pageNum, Integer pageSize, String followMemberId) {
        PageHelper.startPage(pageNum,pageSize);
        Supply supply = new Supply();
        supply.setReleaseMember(followMemberId);
        List<Supply> list = supplyMapper.selectSupplyList(supply);
        for (Supply S : list) {
            String[] imgUrls = S.getImgUrls().split(",");
            S.setImgUrls(imgUrls[0]);
            Company company = companyService.selectCompanyByMemberId(S.getReleaseMember());
            Member member = memberService.selectMemberById(S.getReleaseMember());
            if (company != null) {
                S.setIsCompany(1);
                S.setMemberName(company.getCompanyName());
                S.setHeadpic(company.getCompanyAvatar());
                S.setMemberCompanyId(S.getReleaseMember());
            } else {
                S.setIsCompany(0);
                S.setMemberName(member.getUsername());
                S.setHeadpic(member.getHeadpic());
                S.setMemberCompanyId(S.getReleaseMember());
            }

            // 取消关注供应数字提示
            JiaqinFollowMember followMember = new JiaqinFollowMember();
            followMember.setFollowMemberId(S.getReleaseMember());
            List<JiaqinFollowMember> followMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(followMember);
            if (followMemberList.size() > 0) {
                for (JiaqinFollowMember JFM : followMemberList) {
                    JFM.setId(JFM.getId());
                    JFM.setSupplyNum(0);
                    jiaqinFollowMemberService.updateJiaqinFollowMember(JFM);
                }
            }

        }
        PageInfo<Supply> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<Supply> selectAllSupply() {
        return supplyMapper.selectAllSupply();
    }
}
